<template>
  <div class="page-manage-check">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item :label="$t('coupon.shopName') + ':'">
            <el-input
              v-model="searchForm.shopName"
              style="min-width: 240px;"
              clearable
              :placeholder="$t('coupon.pleEntShopName')"
            />
          </el-form-item>
          <el-form-item
            :label="$t('formData.timeLimit') + ':'"
            class="date-range-param"
          >
            <el-select
              v-model="datePickerType"
              class="date-picker-type"
              @change="setdatePickerType(datePickerType)"
            >
              <el-option
                v-for="item in datePickerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-date-picker
              v-model="dateRangeParam"
              :type="datePickerType"
              clearable
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              :range-separator="$t('date.tip')"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="searchChange"
            >
              {{ $t('order.query') }}
            </div>
            <div
              class="default-btn"
              @click="resetSearchForm"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="table-box">
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
      >
        <el-tab-pane
          :label="$t('shopWallet.incomeCheck')"
          name="revenue"
        >
          <revenue ref="revenueRef" />
        </el-tab-pane>
        <el-tab-pane
          :label="$t('shopWallet.refundCheck')"
          name="refunds"
        >
          <refunds ref="refundsRef" />
        </el-tab-pane>
      </el-tabs>
      <div class="export-btn">
        <el-button
          v-if="isAuth('pay:refund:excel')"
          :icon="Download"
          @click="exportFrom()"
        >
          {{ $t('order.export') }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import revenue from './components/revenue.vue'
import refunds from './components/refunds.vue'
import { Download } from '@element-plus/icons-vue'
import { nextTick, onMounted, reactive } from 'vue'
import moment from 'moment'
import { ElMessage, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'

const Data = reactive({
  activeName: 'revenue', // 对账类型 0支出 1 收入
  datePickerType: 'daterange', // 日期筛选类型
  dateRangeParam: [moment().add(-7, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'), moment().add(-1, 'days').endOf('day').format('YYYY-MM-DD HH:mm:ss')],
  searchForm: {
    startTime: '',
    endTime: '',
    shopName: ''
  },
  tableData: [],
  datePickerTypeOptions: [
    {
      label: $t('date.daterange'),
      value: 'daterange'
    },
    {
      label: $t('date.monthrange'),
      value: 'monthrange'
    }
  ]
})

const { activeName, datePickerType, dateRangeParam, searchForm, datePickerTypeOptions } = toRefs(Data)

onMounted(() => {
  searchChange()
})

const handleClick = () => {
  getData()
}

const revenueRef = ref()
const refundsRef = ref()
const getData = () => {
  nextTick(() => {
    if (Data.activeName === 'revenue') {
      revenueRef.value.getDataDetail(JSON.parse(JSON.stringify(Data.searchForm)))
    } else if (Data.activeName === 'refunds') {
      refundsRef.value.getDataDetail(JSON.parse(JSON.stringify(Data.searchForm)))
    }
  })
}

const setdatePickerType = (val) => {
  Data.datePickerType = val
}

// 条件查询
const searchChange = () => {
  if (!Data.dateRangeParam) {
    return ElMessage.error($t('coupon.pleaseSelTime'))
  }
  Data.searchForm.startTime = Data.dateRangeParam ? Data.dateRangeParam[0] : ''
  Data.searchForm.endTime = Data.dateRangeParam ? Data.dateRangeParam[1] : ''
  getData()
}

/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const resetSearchForm = () => {
  Data.searchForm.shopName = ''
  Data.dateRangeParam = ''
}

const exportFrom = () => {
  if (!Data.dateRangeParam) {
    ElMessage.warning($t('tip.select') + $t('formData.timeLimit'))
    return
  }
  Data.searchForm.startTime = Data.dateRangeParam ? Data.dateRangeParam[0] : ''
  Data.searchForm.endTime = Data.dateRangeParam ? Data.dateRangeParam[1] : ''
  const loading = ElLoading.service({
    lock: true,
    target: '.table-box',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/accountDetail/getPayAndRefundInfoForm'),
    method: 'get',
    params: http.adornParams({
      ...Data.searchForm
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    let fileName = $t('shopWallet.riconciliazioneFinanziaria')
    if (Data.dateRangeParam[0].split(' ')[0] !== Data.dateRangeParam[1].split(' ')[0]) {
      fileName = fileName + '(' + Data.dateRangeParam[0].split(' ')[0] +
        ' ' + $t('date.tip') + ' ' +
        Data.dateRangeParam[1].split(' ')[0] + ')'
    } else {
      fileName = fileName + `(${Data.dateRangeParam[0].split(' ')[0]})`
    }
    fileName = fileName + '.xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  }).catch((e) => {
    loading.close()
  })
}
</script>

<style lang="scss" scoped>
.page-manage-check {
  .search-bar {
    padding-bottom: 25px;

    .input-row {
      .default-btn {
        margin-left: 20px;
      }
    }
  }
}

.table-box {
  position: relative;

  .export-btn {
    position: absolute;
    right: 0;
    top: -5px;
  }
}

.date-picker-type {
  width: 120px !important;
}

:deep(.date-picker-type .el-input--suffix) {
  width: 120px !important;
}

:deep(.el-range-separator) {
  width: 18px;
}

:deep(.el-date-editor--daterange) {
  width: 300px !important;
}

:deep(.date-range-param .el-form-item__label:before) {
  color: #F56C6C;
  margin-right: 4px;
  content: '*';
}

:deep(.search-bar .input-row .el-form-item__content .el-input) {
  width: 100%;
}
</style>
